import SwiftUI
import Combine

// 视频播放管理器 - 确保同时只有一个视频播放，支持预加载
class VideoPlaybackManager: ObservableObject {
    @Published var currentPlayingVideoId: String?
    @Published var preloadVideoId: String?  // 预加载的视频ID
    private var cancellables = Set<AnyCancellable>()
    
    static let shared = VideoPlaybackManager()
    
    private init() {}
    
    // 开始播放视频
    func startPlaying(videoId: String) {
        // 如果当前有视频在播放，先停止
        if let currentId = currentPlayingVideoId, currentId != videoId {
            stopCurrentVideo()
        }
        
        currentPlayingVideoId = videoId
        print("🎬 开始播放视频: \(videoId)")
    }
    
    // 停止当前视频
    func stopCurrentVideo() {
        if let currentId = currentPlayingVideoId {
            print("⏹️ 停止播放视频: \(currentId)")
            currentPlayingVideoId = nil
        }
    }
    
    // 检查视频是否应该播放
    func shouldPlay(videoId: String) -> Bool {
        return currentPlayingVideoId == videoId
    }
    
    // 暂停所有视频
    func pauseAllVideos() {
        currentPlayingVideoId = nil
        preloadVideoId = nil
        print("⏸️ 暂停所有视频")
    }
    
    // 设置预加载视频
    func setPreloadVideo(videoId: String?) {
        preloadVideoId = videoId
        if let videoId = videoId {
            print("🔄 预加载视频: \(videoId)")
        }
    }
    
    // 检查视频是否应该预加载
    func shouldPreload(videoId: String) -> Bool {
        return preloadVideoId == videoId
    }
}
